let Koa = require('koa');

let app = new Koa();

let bodyparser = require('koa-bodyparser');

let static = require('koa-static');

let router = require('koa-router')();

let path = require('path');

let query = require('./db/index');

let authentication = require('./middleware/authentication');

//处理静态资源的中间件
app.use(static(path.join(__dirname,'./public/')));

app.use(authentication());

//处理前端post put传递的参数，放到ctx.request.body
app.use(bodyparser())

app.use(router.routes());

app.use(router.allowedMethods());

//查询

//分页的sql：select * from bloglist limit 起始下标,每页条数`

//查询总条数：select count(*) from  bloglist

router.get('/api/list',async ctx => {
    //pagenum 页数     limit：每页的条数
    let {pagenum=1,limit=2} = ctx.query;
    // ctx.body = 123
    let startIndex = (pagenum-1)*limit;
    let list = await query(`select * from bloglist limit ${startIndex},${limit}`);
    let total = await query('select count(*) from bloglist');
    console.log(total);
    ctx.body = {
        code:1,
        data:list,
        total:total[0]['count(*)']
    }
})

//发表博客
router.post('/api/add',async ctx => {
    let time = new Date();
    let {title,con,username} = ctx.request.body;
    //容错处理
    if(title && con &&username){
        try{
            //尝试执行
            await query('insert into bloglist (title,con,time,username) values (?,?,?,?)',[title,con,time,username]);
            ctx.body = {
                code:1,
                msg:'添加成功'
            }
        }catch(e){ //e:错误对象
            ctx.body = {
                code:0,
                msg:e
            }
        }
    }else{
        ctx.body = {
            code:0,
            msg:'参数有误'
        }
    }
})

//删除博客

router.delete('/api/del',async ctx => {
    let {id} = ctx.query;
    if(id){
        try{
            await query('delete from bloglist where id=?',[id]);
            ctx.body = {
                code:1,
                msg:'删除成功'
            }
        }catch(e){
            ctx.body = {
                code:0,
                msg:e
            }
        }
    }else{
        ctx.body = {
            code:0,
            msg:'参数有误'
        }
    }
})

//修改博客
router.put('/api/update',async ctx => {
    let {title,con,id} = ctx.request.body;
    //容错处理
    if(title && con &&id){
        try{
            //尝试执行
            await query('update bloglist set title=?,con=? where id=?',[title,con,id]);
            ctx.body = {
                code:1,
                msg:'修改成功'
            }
        }catch(e){ //e:错误对象
            ctx.body = {
                code:0,
                msg:e
            }
        }
    }else{
        ctx.body = {
            code:0,
            msg:'参数有误'
        }
    }
})

app.listen(3000,() => {
    console.log("服务启动成功")
})